﻿namespace Sidvall.Data
{
	public class SaveContext<T> : ISaveContext
	{
		#region Public Members

		public T Item { get; set; }
		public SaveSettings Settings { get; set; }

		#region CriteriaId

		protected string CriteriaId
		{
			get
			{
				if (this.Settings != null)
					return this.Settings.CriteriaId;
				return null;
			}
		}

		#endregion
		#region Parameters

		protected ParameterCollection Parameters
		{
			get
			{
				if (this.Settings != null)
					return this.Settings.Parameters;
				return null;
			}
		}

		#endregion

		#region GetDataRowStateResolved

		private DataRowState? _DataRowStateResolved;
		public DataRowState GetDataRowStateResolved(DataRowState defaultState)
		{
			return GetDataRowStateResolved(defaultState, false);
		}
		public DataRowState GetDataRowStateResolved(DataRowState defaultState, bool refresh)
		{
			IDataRowContextProvider provider;

			if ((_DataRowStateResolved == null) || (refresh))
			{
				provider = this.Item as IDataRowContextProvider;
				if (provider != null)
					_DataRowStateResolved = SaveSettings.GetDataRowStateResolved(GetSaveMode(), provider);
			}
			if (_DataRowStateResolved == null)
				return defaultState;
			return _DataRowStateResolved.Value;
		}

		#endregion
		#region GetOperationResolved

		public string GetOperationResolved(DataRowState defaultState)
		{
			DataRowState state;

			state = GetDataRowStateResolved(defaultState);

			return Sidvall.Security.Operations.GetOperation(state);
		}

		#endregion
		#region GetSaveMode

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
		public SaveMode GetSaveMode()
		{
			if (this.Settings != null)
				return this.Settings.Mode;
			return SaveMode.Default;
		}

		#endregion

		#region ISaveContext Members

		string ICriteria.CriteriaId
		{
			get
			{
				return this.CriteriaId;
			}
		}
		ParameterCollection IParameterProvider.Parameters
		{
			get
			{
				return this.Parameters;
			}
		}
		object ISaveContext.Item
		{
			get
			{
				return this.Item;
			}
		}

		#endregion

		#endregion
	}
}
